import md5 from 'md5';
import { isPlainObject, camelCase } from 'lodash';
import { ModelAttributes, DataTypes } from 'sequelize';
import moment from 'moment';


/**
 * 删除含有 null 或者 undefined 的字段
 * @param data 要检测的数据
 */
export function deleteNullOrUndefinedField(data: object) {
  return Object.keys(data).reduce((pre, key) => {
    let item = data[key];
    if (isPlainObject(item)) {
      item = deleteNullOrUndefinedField(item);
    }
    if (item !== null && item !== undefined && item !== '') {
      pre[key] = item; // eslint-disable-line no-param-reassign
    }
    return pre;
  }, {});
}

// 加密支付
export const getSign = (params: any, partnerKey: string) => {
  const keys = Object.keys(params);

  keys.sort((a, b) => a.charCodeAt(0) - b.charCodeAt(0));
  const stringA = keys.map(it => it + '=' + params[it]).join('&');
  const stringSignTemp = `${stringA}&key=${partnerKey}`; //注：key为商户平台设置的密钥key
  return md5(stringSignTemp).toUpperCase();
}

// 处理微信的支付时间
export const toPayTime = (date: string) => {
  if (date.length !== 14) return date;
  const YYYY = date.substring(0, 4);
  const MM = date.substring(4, 6);
  const DD = date.substring(6, 8);
  const HH = date.substring(8, 10);
  const mm = date.substring(10, 12);
  const ss = date.substring(12, 14);
  return `${YYYY}-${MM}-${DD} ${HH}:${mm}:${ss}`;
};

export const modelToCamelCase = (data: string) =>
  camelCase(data).replace(/^\S/, s => s.toUpperCase());


/**
 * 每个字段都应该有的值
 * 以下字段
 * 每个表必须有
 */
export function getDefaultFields(): ModelAttributes {
  return {
    create_at: {
      type: DataTypes.BIGINT,
      allowNull: false,
      comment: '创建时间'
    },
    update_at: {
      type: DataTypes.BIGINT,
      allowNull: false,
      comment: '最后更新时间'
    },
    delete_at: {
      type: DataTypes.BIGINT,
      allowNull: true,
      comment: '删除时间'
    },
    opa_user: {
      type: DataTypes.STRING(30),
      allowNull: false,
      defaultValue: '',
      comment: '操作人'
    },
    shop_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      defaultValue: null,
      comment: '商家ID，预留SASS功能'
    },
    is_delete: {
      type: DataTypes.INTEGER().UNSIGNED,
      allowNull: false,
      defaultValue: '0',
      comment: '是否删除，0->存在，1->删除'
    },
  }
}

export function getCurrentStimp() {
  return Math.floor(Date.now() / 1000)
}

// 元 -> 分
export const yuanToFen = (data, keys) => {
  keys.forEach((key: string) => {
    data[key] = data[key] ? data[key] * 100 : 0
  });
  return data;
}

// 生成orderID
export const getOrderId = () => {
  const createTime = moment().unix();
  const tmpOrder = `${Math.random().toString().slice(-5)}${createTime}`;
  const order_id = tmpOrder.substring(tmpOrder.length - 32);
  return order_id;
}


export const toDate = (time) => moment(time * 1000).format('YYYY-MM-DD HH:mm:ss')